<template>
	<div>
		<el-row type="flex" justify="space-around">
			<el-col :span="4" class="leftInfo">
				<!-- 树形 -->
				<div class="leftTop">
					<span>部门名称</span>
				</div>
				<el-tree ref="treeinfo" highlight-current class="treeInfo" :data="treeInfo" :props="defaultProps" @node-click="treeNodeClick"
				 highlight-current node-key="id" :default-expanded-keys="expandedKeys"></el-tree>
			</el-col>
			<el-col :span="19" class="rightInfo">
				<!-- 搜索框 -->
				<el-form :inline="true" ref="searchForm" class="search" :model="searchForm" v-if="checkPermission(['sys:user:search'])">
					<el-form-item label="用户名:">
						<el-input size="mini" v-model="searchForm.userName" clearable></el-input>
					</el-form-item>
					<el-form-item label="手机号码:">
						<el-input style="float: left;" size="mini" v-model="searchForm.phoneNumber" clearable onkeyup="this.value=this.value.replace(/[^\d]/g,'') "
						 onafterpaste="this.value=this.value.replace(/[^\d]/g,'') "></el-input>
					</el-form-item>
					<el-form-item label="邮箱:">
						<el-input style="float: left;" size="mini" v-model="searchForm.email" clearable></el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" icon="el-icon-search" size="small" @click="searchFormClick()">搜索</el-button>
						<el-button type="primary" size="small" @click="searchFormReset()">重置</el-button>
					</el-form-item>
				</el-form>
				<!-- 表格展示 -->
				<div class="tableInfo">
					<div class="leftButton">
						<el-button v-permission="['sys:user:add']" :disabled="addButtonState" type="primary" size="small" @click="AddClick()">新增</el-button>
					</div>
					<el-table :data="tableData" style="width: 95%" highlight-current-row border :header-cell-style="{'text-align':'center'}"
					 :cell-style="{'text-align':'center'}">
						<el-table-column prop="userId" label="id"></el-table-column>
						<el-table-column prop="username" label="用户名称"></el-table-column>
						<el-table-column prop="phoneNumber" label="手机号码"></el-table-column>
						<el-table-column prop="email" label="电子邮箱"></el-table-column>
						<el-table-column prop="creatTime" label="创建时间"></el-table-column>
						<el-table-column prop="updateTime" label="更新时间"></el-table-column>
						<el-table-column fixed="right" label="操作" v-if="checkPermission(['sys:user:setRole','sys:user:update','sys:user:del'])">
							<template slot-scope="scope">
								<el-button v-permission="['sys:user:setRole']" @click="EditRoleClick(scope.row)" type="text" size="small">编辑角色</el-button>
								<el-button v-permission="['sys:user:update']" @click="EditClick(scope.row)" type="text" size="small">编辑</el-button>
								<el-button v-permission="['sys:user:del']" @click="DeleteClick(scope.row)" type="text" size="small">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-pagination v-if="paginationState" @size-change="paginationSizeChange" @current-change="paginationCurrentChange"
					 :current-page="pageInfo.currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pageInfo.currentSize" layout="total, sizes, prev, pager, next, jumper"
					 :total="pageInfo.total">
					</el-pagination>
				</div>
			</el-col>
		</el-row>
		<!-- 用户新增的修改的弹窗 -->
		<div>
			<el-dialog :title="dialogName[dialogType]" width="25%" :visible.sync="addDialogShow" class="addUserInfo">
				<el-form :rules="rules" ref="ruleForm" :model="addInfoForm">
					<el-form-item label="用户名称" label-width="100px" prop="username">
						<el-input clearable v-model="addInfoForm.username" size="medium"></el-input>
					</el-form-item>
					<el-form-item label="手机号码" label-width="100px" prop="phoneNumber">
						<el-input clearable v-model="addInfoForm.phoneNumber" maxlength="11" size="medium" show-word-limit onkeyup="this.value=this.value.replace(/[^\d]/g,'') "
						 onafterpaste="this.value=this.value.replace(/[^\d]/g,'')"></el-input>
					</el-form-item>
					<el-form-item label="邮箱号码" label-width="100px">
						<el-input clearable v-model="addInfoForm.email" size="medium"></el-input>
					</el-form-item>
					<el-form-item v-if="dialogType===0" label="密码" label-width="100px" prop="password">
						<el-input clearable v-model="addInfoForm.password" placeholder="请输入密码" show-password size="medium"></el-input>
					</el-form-item>
					<el-form-item v-else label="密码" label-width="100px">
						<el-input clearable v-model="addInfoForm.password" placeholder="请输入密码" show-password size="medium"></el-input>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="cancelForm">取 消</el-button>
					<el-button v-if="resetButtonState" @click="resetForm()">重置</el-button>
					<el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
				</div>
			</el-dialog>
		</div>
		<div>
			<el-dialog title="角色修改" width="33%" :visible.sync="editRoleDialogShow">
				<el-transfer :titles="transferTitle" filterable :filter-method="filterMethod" filter-placeholder="请输入角色名称" v-model="transferDataValue"
				 :data="rolesList" :props="transferProps">
				</el-transfer>
				<div slot="footer" class="dialog-footer">
					<el-button @click="cancelRoleForm()">取 消</el-button>
					<el-button type="primary" @click="submitRoleForm">确 定</el-button>
				</div>
			</el-dialog>
		</div>
	</div>
</template>

<script>
	import {
		getUserInfoByDepartment,
		addUserInfo,
		deleteUserInfoByUserId,
		modifyUserInfo,
		getUserRoleInfo,
		EditUserRoleInfo,
		getDepartmentTree,
		getUserRoleAll,
		searchUserInfo
	} from '@/api/user.js'

	import Public from '@/views/mixin/PublicHandler.js'
	export default {
		mixins: [Public],
		data() {
			return {
				//搜索信息
				searchForm: {
					userName: '',
					phoneNumber: '',
					email: ''
				},
				//新增用户窗口状态
				addDialogShow: false,
				//当前树节点id
				currentTreeId: '',
				//新增用户信息
				addInfoForm: '',
				//表格信息
				tableData: [],
				dialogName: ["新增用户", "修改用户"],
				//树默认选中节点
				expandedKeys: [],
				//弹出框类型 0 新增 1 修改
				dialogType: 0,
				//分页状态
				paginationState: true,
				//设置角色窗口
				editRoleDialogShow: false,
				//角色列表
				rolesList: [],
				//树形数据
				treeInfo: [],
				//穿梭框
				transferProps: {
					key: 'roleId',
					label: 'roleName'
				},
				//穿梭框选中值
				transferDataValue: [],
				transferTitle: ["已选中", "未选中"]
			};
		},
		//监听属性 类似于data概念
		computed: {
			//新增按钮状态
			addButtonState() {
				if (!this.currentTreeId) {
					return true
				} else {
					return false
				}
			},
			//重置按钮状态
			resetButtonState() {
				if (this.dialogType === 1) {
					return false
				} else {
					return true
				}
			}
		},
		//监控data中的数据变化
		watch: {
			treeInfo() {
				this.paginationState = true
				this.$nextTick(() => {
					this.$refs.treeinfo.setCurrentKey("1251544671117774848");
					this.currentTreeId = "1251544671117774848"
					this.getTableInfo()
					this.expandedKeys = ["1251544671117774848"]
				})
			}
		},
		//方法集合
		methods: {
			/**
			 * 树结构
			 */
			//获取左侧树信息
			getLeftTreeInfo() {
				getDepartmentTree().then(response => {
					const {
						data
					} = response
					this.treeInfo = data
					return data
				})
			},
			//点击树节点
			treeNodeClick(data) {
				this.currentTreeId = data.id
				this.getTableInfo()
			},

			/**
			 * 搜索
			 */
			//充值搜索信息
			searchFormReset() {
				this.searchForm = {}
				this.getLeftTreeInfo()
			},
			//点击搜索按钮
			searchFormClick() {
				searchUserInfo(this.searchForm).then(response => {
					const {
						data
					} = response
					this.tableData = data
				})
				this.currentTreeId = null
				this.expandedKeys = []
				this.$refs.treeinfo.setCurrentKey()
				this.paginationState = false
			},

			/**
			 * 表结构
			 */
			//点击新增按钮
			AddClick() {
				this.dialogType = 0
				this.addInfoForm = {}
				this.addDialogShow = true
			},
			//获取表数据
			getTableInfo() {
				const queryData = {
					departmentId: this.currentTreeId,
					page: this.pageInfo.currentPage,
					size: this.pageInfo.currentSize
				}
				getUserInfoByDepartment(queryData).then(response => {
					const {
						data
					} = response
					this.tableData = data.records
					this.pageInfo.total = data.total
					this.pageInfo.currentPage = data.current
					this.pageInfo.currentSize = data.size
				})
			},
			//编辑按钮
			EditClick(row) {
				this.dialogType = 1
				this.addInfoForm = Object.assign({}, row)
				this.addDialogShow = true
			},
			//编辑角色按钮
			EditRoleClick(row) {
				this.addInfoForm = Object.assign({}, row)
				getUserRoleInfo(row.userId).then(response => {
					const {
						data
					} = response
					this.transferDataValue = data
				})
				this.editRoleDialogShow = true
			},
			//删除按钮
			DeleteClick(row) {
				this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					deleteUserInfoByUserId(row.userId).then(response => {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.getTableInfo()
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			//分页条数改变
			paginationSizeChange(data) {
				this.pageInfo.currentSize = data
				this.getTableInfo()
			},
			//页面数更新
			paginationCurrentChange(data) {
				this.pageInfo.currentPage = data
				this.getTableInfo()
			},

			/**
			 * 新增修改窗口
			 */
			//取消按钮
			cancelForm() {
				this.addInfoForm = {}
				this.addDialogShow = false
			},
			//重置按钮
			resetForm() {
				this.addInfoForm = {}
			},

			//提交
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if (this.dialogType === 1) {
							this.modifyUser()
						} else {
							this.addUser()
						}
						this.addDialogShow = false
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			//新增用户
			addUser() {
				this.addInfoForm.departmentId = this.currentTreeId
				addUserInfo(this.addInfoForm).then(response => {
					this.$alert("添加用户成功", "")
					this.addDialogShow = false
					this.getTableInfo()
				})
			},
			//修改用户
			modifyUser() {
				this.$confirm('此操作将修改该记录, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					modifyUserInfo(this.addInfoForm).then(response => {
						this.$message({
							type: 'success',
							message: '修改成功!'
						});
						this.getTableInfo()
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '修改已取消'
					});
				});
			},
			//修改角色窗口
			//提交角色信息
			submitRoleForm() {
				const data = {
					userId: this.addInfoForm.userId,
					rolesId: this.transferDataValue
				}
				this.$confirm('此操作将修改该记录, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					EditUserRoleInfo(data).then(response => {
						this.$message({
							type: 'success',
							message: '修改成功!'
						});
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '修改已取消'
					});
				});
				this.editRoleDialogShow = false
			},
			//穿梭框过滤方法
			filterMethod(query, item) {
				return item.roleName.indexOf(query) > -1
			},
			//获取角色用户列表
			getRoleList() {
				getUserRoleAll().then(response => {
					const {
						data
					} = response
					this.rolesList = data
				}).catch(error => {
					console.log(error)
				})
			},
			//取消角色编辑页面
			cancelRoleForm() {
				this.editRoleDialogShow = false
			},
		},
		//生命周期 - 创建完成（可以访问当前this实例）
		created() {
			this.getLeftTreeInfo()
			this.rules = {
				username: [{
					required: true,
					message: '请输入用户名称',
					trigger: 'blur'
				}],
				phoneNumber: [{
					required: true,
					message: '请输入手机号码',
					trigger: 'blur'
				}],
				password: [{
					required: true,
					message: '请输入密码',
					trigger: 'blur'
				}]
			}
			this.rolesList = this.getRoleList()
		},
		//生命周期 - 挂载完成（可以访问DOM元素）
		mounted() {}
	};
</script>
<style scoped lang="scss">
	.leftInfo {
		border: #001528;
		background-color: #ffffff;
		margin-top: 0.625rem;
		border-radius: 14px;
		box-shadow: 10px 10px 5px rgba(100, 100, 100, .5);

		.leftTop {
			text-align: center;
			font-size: 23px;
			border-bottom-style: solid;
			border-width: 4px;
			border-color: #F3F3F4;
		}

		.treeInfo {
			margin: 20px 10px 20px 20px;
		}
	}

	.rightInfo {
		.tableInfo {
			background-color: #ffffff;
			margin-top: 0.625rem;
			min-height: 208px;
			border-radius: 10px;
			box-shadow: 10px 10px 5px rgba(100, 100, 100, .5);
			padding-bottom: 1.25rem;

			.leftButton {
				padding-left: 1.9375rem !important;
				padding-top: 10px;
			}

			.el-table {
				margin-top: 0.625rem;
				margin-left: auto;
				margin-right: auto;
				margin-bottom: 20px;
				font-size: 15px;
			}

			.el-pagination {
				margin-left: 1.375rem;
				padding-top: 10px;
				padding-bottom: 20px;
			}
		}

		.search {
			margin-top: 0.625rem;
			border-radius: 5px;
			background-color: #FFFFFF;
			display: flex;
			flex-direction: row;
			justify-content: space-around;
			box-shadow: 10px 10px 5px rgba(100, 100, 100, .5);

			.el-form-item {
				margin-bottom: 0 !important;
				margin-left: 20px;
			}
		}
	}

	.addUserInfo {
		.el-input {
			width: 13.5rem;
		}

		.el-form-item {
			padding-left: 10px;
		}
	}
</style>
